const puppeteer = require("puppeteer-core");
const callUrl = require("./url/call");
const config = require("./config");

async function callback() {
  const browser = await puppeteer.launch({
    headless: false, //有浏览器界面启动
    slowMo: 100, //放慢浏览器执行速度，方便测试观察
    ignoreHTTPErrors: false,
    defaultViewport: { width: 1400, height: 700 },
    args: [
      //启动 Chrome 的参数，详见上文中的介绍
      // "–no-sandbox",
      // '--start-fullscreen'
    ],
  });

  console.log(`\x1B[33m ========---任务执行开始---========  \x1B[0m`);

  const page = await browser.newPage();
  await page.goto("https://www.baidu.com/");
  await wait(1);

  for (let i = 0; i < callUrl.length; i++) {
    try {
      await page.goto(callUrl[i]);
      await page.setUserAgent(
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
      );
      //等待验证码弹框
      await wait(4);

      //取消输入验证码
      let cbtn = await page.$(
        ".imlp-widget-captcha-button.imlp-widget-captcha-button--cancel"
      );
      cbtn?.click();
      await page.evaluate(`
  document.querySelector('.passMod_dialog-wrapper.passMod_show')?.remove()
`);

      await wait(1);
      //点击输入手机号
      // let checkTel = await page.$(".pc-icon-leave-tel");
      // await checkTel.click();
      // //输入手机号
      // let inp = await page.$(".leavetel-input");
      // await inp.type(config.phone);
      // //确定
      // let btn = await page.$(".leavetel-callback");
      // await btn.click();
      if (config.name) {
        //输入姓名
        let text = await page.$(
          ".imlp-component-typebox-input.pc-imlp-component-typebox-input"
        );
        await text?.type(config.name);
        await wait(0.1);
        //发送
        let sbtn = await page.$(
          ".imlp-component-typebox-send-btn.pc-imlp-component-typebox-send"
        );
        await sbtn?.click();
      }

      await wait(30);
    } catch (e) {
      console.log(`\x1B[31m ==${callUrl[i]}--失败--${e}===  \x1B[0m`);
    }
  }
  await page.close();
  browser.close();

  console.log(`\x1B[33m ========---任务执行结束---========  \x1B[0m`);
}

callback();

function wait(time) {
  return new Promise((res) => {
    setTimeout(() => {
      res();
    }, time * 1000);
  });
}
